/**
	cols: type:1表示按钮集合 没有表示正常的数据展示
	dataId:""//数据id标识字段
	dataType:"json",
	url;"请求地址"，
	seriesFormParam：//格式化数据
	serilizeData://处理返回数据,
	editUrl:"",//编辑地址
	delUrl:"",删除地址,
	success:接口调用成功毁掉，type(del,edit,add...)
	error接口调用失败回掉
**/
var defaultSetting = {};
var table = function(option) {
	option.$p = this;
    var myTable = new jqTable(option);
    myTable.loadData();
    return myTable;
};
function jqTable(option){
	this.content = "";
    this.colNames = [];
    this.btnList = [];
    this.trList = [];
    this.dataList = [];
    this.editList = [];
    this.option = $.extend(defaultSetting, option);
    this.cols = this.option.cols;
    this.dataType = option.dataType;
    this.$p = option.$p;
    this.createTable();
}
jqTable.prototype = {
	append:function(args){
		return this.$p.append(args);
	},
	find:function(str){
		return $el.find(str);
	},
	reload:function(){
    	this.$tbody.html("");
    	this.loadData();
    },
    loading:function(){
    	if(!this.$loading){
    		this.$loading = $("<div>loading...</div>");
    	}
    	this.$loading.show();
    },
    initBody:function(){
    	this.$tbody = $("<tbody>");
    	return this.$tbody;
    },
    createTable: function() {
        this.$t = $('<table cellpadding="0" border="1" cellspacing="0"></table>');
        this.$t.append(this.initHead());
        this.$t.append(this.initBody());
        //this.renderDataList(this.option.dataList);
        this.initEvent();
        this.append(this.$t);
    },
    isCheckBox: function(type) {
        return type === "checkbox";
    },
    isNormal: function(type) {
        return !type || type === "normal";
    },
    isBtn: function(type) {
        return type === "button";
    },
    initHead: function() {
        var self = this,
            $thead = $("<thead>");
        $.each(self.cols, function(index, el) {
            var $th = $("<th>"),
                type = el.type,
                title = el.title;
            if (self.isCheckBox(type)) {
                self.generateCheckBox($th, -1);
                //$th.append($("<input type='checkbox'data-rowid='-1'>"));
            } else if (self.isNormal(type)) {
                $th.text(title);
            } else if (self.isBtn(type)) {
                $th.text(title);
            }
            $thead.append($th);
        });
        return $thead;
    },
    getData: function() {

    },
    getRowData: function(rowId) {
        return this.dataList[rowId];
    },
    getIdItem: function(data) {
        if (!this.option.dataId || !data[this.option.dataId]) {
            throw new Error("There is no id for data!");
        }
        return data[this.option.dataId];
    },
    generateCheckBox: function($el, index) {
        $el.append($("<input class='input_control' type='checkbox' data-rowid='" + index + "'>"));
    },
    isChecked:function(el){
    	return el.checked;
    },
    getCheckboxs:function(){
    	return this.$t.find(".input_control");
    },
    //初始化事件
    initEvent:function(){
    	this.chooseTr = {};
    	/**
		input框事件初始化
    	*/
    	var $inputs = this.getCheckboxs(),
    		self = this;
    	$inputs.on("click",function(){
    		var $el = $(this),
    			rowid = $el.data("rowid");
    		if(rowid==-1){
    			var isChecked = self.isChecked(this);
    			console.log("isChecked:"+isChecked);
				$inputs.prop("checked",isChecked);
    		}
    	});
    	$inputs.on("change",function(){
    		var isChecked = self.isChecked(this),
    			rowid = $(this).data("rowid"),
    			value = isChecked?self.getTr(rowid):null;
    		if(rowid==-1){
    			$.each($inputs,function(index,el){
    				var thisId = $(this).data("rowid"),
    					value = isChecked?self.getTr(thisId):null;
    				self.chooseTr[thisId] = value;
    			});
    		}else{
    			self.chooseTr[rowid] = self.getTr(rowid);
    		}	
    	});
    },
    generateBtn: function($td, value, index, id) {
        var data = this.dataList[index]; //.text(el.title);
        $.each(value.btns, function(i, e) {
            var $span = $("<span class='control_" + i + "' data-rowid='" + index + "' data-id='" + id + "'>");
            $span.text(e.title);
            $span.on("click", data, e.callback);
            $td.append($span);
        });
    },
    geneateNormal: function($td, value) {
        $td.text(value); //.data("name",el);
        $td.attr("title", value);
    },
    renderData: function(data, index) {
        var dataHTML = '',
            $tr = $("<tr data-rowid='" + index + "'>"),
            self = this,
            id = self.getIdItem(data);
        this.dataList.push(data);
        this.trList.push($tr);
        $.each(self.cols, function(key, el) {
            var name = el.name || el.title || el.type,
                $td = $("<td data-name='" + name + "' data-colid='" + key + "' data-rowid='" + index + "'>"),
                type = el.type,
                value = data[name];
            if (self.isCheckBox(type)) {
                self.generateCheckBox($td, index);
            } else if (self.isNormal(type)) {
                self.geneateNormal($td, value);
            } else if (self.isBtn(type)) {
                self.generateBtn($td, el, index, id);
            }

            $tr.append($td);
        });
        return $tr;
    },
    //刷新数据列表
    renderDataList: function(dataList) {
        var self = this,
            $tbody = this.$tbody;
        this.dataList = [];
        this.editList = [];
        $.each(dataList, function(i, el) {
            $tbody.append(self.renderData(el, i));
        });
        this.$t.append($tbody);
    },
    /**
    获取每一列信息
    */
    getColInfo: function(colid) {
        return this.cols[colid];
    },
    getFieldValue: function(data, name) {
        return data[name];
    },
    //取消编辑
    cancleEdit: function(index) {
        var self = this;
        if (typeof index === "undefined") {
            $.each(self.editList, function(key, el) {
                self.editRow(el, true);
            });
        }
    },
    editRows:function(){
    	var self = this;
    	$.each(this.chooseTr,function(key,el){
    		if(el){
    			self.editRow(+key);
    		}
    	});
    },
    //编辑一行
    editRow: function(index, flag) {
        var $tr = this.trList[index],
            $tds = $tr.find("td"),
            self = this,
            data = self.getRowData(index);
        if ($tr.isEdit() && !flag) {
            return;
        }
        this.editList.push(index);
        $tr.isEdit(flag ? false : true);
        $.each($tds, function(index, el) {
            var $td = $(el),
                name = $td.data("name"),
                colid = $td.data("colid"),
                value = self.getFieldValue(data, name),
                type = self.getColInfo(colid).type;
            if (!self.isNormal(type)) {
                return true;
            }
            var $input = value;
            if (!flag) {
                $input = $("<input type='text' name='" + name + "' value='" + value + "'/>");
            }
            $td.html($input);
        });
    },
    getEditRows: function() {

    },
    getTr: function(rowid) {
        return this.trList[rowid];
    },
    saveEditDatas: function() {
        var self = this,
            dataList = [];
        $.each(this.editList, function(key, el) {
            var dataObj = {};
            data = self.getRowData(el),
                $tr = self.getTr(el),
                modifyData = {};
            dataObj.data = data;
            $inputs = $tr.find("input[type='text']");
            $.each($inputs, function(i, element) {
                var $el = $(element),
                    name = $el.attr("name"),
                    value = $el.val();
                modifyData[name] = value;
                dataObj.modifyData = $.extend({}, data, modifyData);
            });
            dataList.push(dataObj);
        });
        self.cancleEdit();
        return dataList;
    },
    /**
    	显示没有数据
    **/
    showNoData:function(){

    },
    /**
		加载数据接口
    */
    loadData:function(pageNo){
    	var self = this;
    		url = this.option.url,
    		seriesFormParam = this.option.seriesFormParam;
    	if(!this.dataType){
    		return this.renderDataList(this.option.dataList);
    	}
    	$.ajax({
    		url:url,
    		dataType:"json",
    		data:seriesFormParam?seriesFormParam():{},
    		success:function(resp){
    			// self.option.success
    			var data = self.serilizeData ? self.serilizeData(resp):resp;
    			if(!data){
    				data = resp;
    			}
    			if(!data.dataList || data.dataList.length===0){
    				self.showNoData();
    				return;
    			}
    			self.renderDataList();
    		}
    	});
    },
    /**
		表格删除方法
    **/
    delData:function(rowid){
    	var data = this.getRowData(rowid),
    		self = this;
    	if(this.dataType!=="json"){
    		this.find("tr[data-rowid='"rowid+"']").remove();
    	}else{
    		$.ajax({
    			url:self.delUrl,
    			dataType:"json",
    			data:{id:self.getIdItem(data)},
    			type:'post',
    			success:function(resp){
    				self.option.success && self.option.success("del",resp);
    			},
    			error:function(resp){
    				self.option.error && self.option.error("del",resp);
    			}
    		})
    	}
    	this.reload();
    }
}
$.fn.extend({
    /**
        jquery扩展接口
    **/
    jqTable: function(option) {
        return table.call(this, option);
    },
	isEdit: function(flag) {
        if (typeof flag !== "undefined") {
            this.data("isEdit", flag);
            return;
        }
        return this.data("idEdit");
    }    
});
